package com.jeff.android.lab.android.lazy;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

public abstract class LazyFragment extends Fragment {

    public final static String TAG = "LazyFragment";

    private boolean isFirstSetUserVisibleHint = true; //
    private boolean isFirstVisible = true; // 第一次可见
    private boolean isViewCreated = false; // Fragment 视图创建完成

    protected void onFragmentVisibleChange(boolean visible) {
    }

    protected void onLazyLoad() {
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint() && this.isViewCreated) {
            if (this.isFirstVisible) {
                onLazyLoad();
                this.isFirstVisible = false;
            } else {
                onFragmentVisibleChange(true);
            }
        } else {
            if (isFirstSetUserVisibleHint) {
                isFirstSetUserVisibleHint = false;
            } else {
                if (this.isViewCreated)
                    onFragmentVisibleChange(false);
            }
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.isViewCreated = true;
        if (getUserVisibleHint()) {
            if (this.isFirstVisible) {
                onLazyLoad();
                this.isFirstVisible = false;
            } else {
                onFragmentVisibleChange(true);
            }
        }
    }

}
